﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernate;
using AjConsor.Entities;
using NHibernate.Context;

namespace AjConsor.WebNh1
{
    public class Global : System.Web.HttpApplication
    {
        public static ISessionFactory SessionFactory;

        protected void Application_Start(object sender, EventArgs e)
        {
            Configuration configuration = new Configuration();
            configuration.Configure();
            (new SchemaExport(configuration)).Create(false, true);
            SessionFactory = configuration.BuildSessionFactory();

            Consorcio cons1 = new Consorcio()
            {
                Nombre = "Edificio 1",
                Domicilio = "Calle 1"
            };

            Unidad uni1 = new Unidad()
            {
                Descripcion = "Departamento 1"
            };

            Unidad uni2 = new Unidad()
            {
                Descripcion = "Departamento 2"
            };

            cons1.AddUnidad(uni1);
            cons1.AddUnidad(uni2);

            using (var session = SessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.Save(cons1);
                    //session.Save(uni1);
                    //session.Save(uni2);

                    transaction.Commit();
                }
            }
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var session = SessionFactory.OpenSession();
            ManagedWebSessionContext.Bind(HttpContext.Current, session);
            session.BeginTransaction();

            //var session = SessionFactory.OpenSession();
            //session.BeginTransaction();
            //HttpContext.Current.Items["NhSession"] = session;
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            var session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionFactory);

            if (session != null)
            {
                if (session.Transaction != null && session.Transaction.IsActive)
                    session.Transaction.Commit();

                session.Close();
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}